package com.hc.comm.utils;

import java.util.HashMap;
import java.util.Map;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;

import com.hc.comm.model.PushModel;

public class PushUtil {
	private static final String PUSH_APP_SECRET = "5aadd13f2a1223183c51bebf";
	private static final String PUSH_APP_KEY = "01cb1299e2c7fb0b6f1676ff";

	private static JPushClient client;

	public static JPushClient getPushClient() throws Exception {
		if (client == null) {
			client = new JPushClient(PUSH_APP_SECRET, PUSH_APP_KEY);
		}
		
		return client;
	}

	
	public static void push(Runnable runnable) {
		
		ThreadPoolTaskExecutor threadPoolTaskExecutor = SpringContextHolder.getBean("threadPoolTaskExecutor");
		
		threadPoolTaskExecutor.submit(runnable);
	}
	
	@SuppressWarnings("unused")
	public static PushResult sendMessage(PushModel model) {
		PushResult result = null;
		
		if (model != null) {
			try {
				getPushClient();
				result = client.sendMessageAll(model.getJson());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				MyLog.log("sendMessage e = " + e);
			}
			
		}
		
		return result;
	}
	
	
	@SuppressWarnings("unused")
	public static PushResult sendNotification(PushModel model) {
		PushResult result = null;
		
		if (model != null) {
			try {
				getPushClient();
				//result = client.sendNotificationAll(model.getJson());
				client.sendPush(PushPayload.newBuilder()
		                .setPlatform(Platform.all())
		                .setAudience(Audience.all())
		                .setNotification(Notification.alert(model.title)).setMessage(
								Message.newBuilder().setMsgContent(model.getJson())
								.addExtras(model.getExtras()).build())
		                .build());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				MyLog.log("sendNotification e = " + e);
			}
			
		}
		
		return result;
	}
	
	/**
	 * 
	 * 获取regId s格式:yjd_设备regid_android|ios
	 * 
	 * @param s
	 * @return
	 */
	@SuppressWarnings("unused")
	public static PushResult sendMessageWithRegistrationID(String registrationID, PushModel model) {
		PushResult result = null;
		
		if (StringUtil.isNotEmpty(registrationID) && model != null) {
			
			String ids[] = registrationID.split("_");
			
			if (ids != null && ids.length == 2) {
				MyLog.log("sendMessageWithRegistrationID  ids[0] = " + ids[0] + ", registrationID = " + registrationID
						+ ", model.getJson() = " + model.getJson());
				if (StringUtil.isEmpty(ids[0])) {
					return result;
				}
				
				try {
					getPushClient();
					if (ids[1].equalsIgnoreCase("android")) {
						result = client.sendAndroidMessageWithRegistrationID(model.title, model.getJson(), ids[0]);
						
					} else if (ids[1].equalsIgnoreCase("ios")) {
						//result = client.sendIosMessageWithRegistrationID(model.title, model.getJson(), ids[0]);
						result = sendNotificationWithRegistrationID(registrationID, model);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					MyLog.log("sendMessageWithRegistrationID e = " + e);
				}
				
			}
			
		}
		
		return result;
	}

	
	@SuppressWarnings("unused")
	public static PushResult sendNotificationWithRegistrationID(String registrationID, PushModel model) {
		PushResult result = null;
		if (StringUtil.isNotEmpty(registrationID) && model != null) {
			
			String ids[] = registrationID.split("_");
			if (ids != null && ids.length == 2) {
				try {
					if (StringUtil.isEmpty(ids[0])) {
						return result;
					}
					
					String alert = model.title;
					
					HashMap<String, String> extras = new HashMap<String, String>();
					extras.put("content", model.getJson());
					getPushClient();

					if (ids[1].equalsIgnoreCase("android")) {
						result = client.sendAndroidNotificationWithRegistrationID(model.title, alert, extras, ids[0]);
						
					} else if (ids[1].equalsIgnoreCase("ios")) {
						result = client.sendIosNotificationWithRegistrationID(alert, extras, ids[0]);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					MyLog.log("sendNotificationWithRegistrationID e = " + e);
				}
				
			}
			
		}
		
		return result;
	}
	
	
	/**
	 * 
	 * 无记录发送推送（测试）
	 * 
	 * @param content
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unused")
	private static PushResult sendNotificationAll(String content) throws Exception {
		PushResult result = null;
		if (StringUtil.isNotEmpty(content)) {
			getPushClient();
			result = client.sendNotificationAll(content);
		}
		return result;
	}

	/**
	 * 
	 * 无记录发送推送（测试）
	 * 
	 * @param registrationID
	 *            推送设备regId
	 * @param content
	 *            推送内容
	 * @param extras
	 *            附加属性
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes", "unchecked", "unused" })
	private static PushResult pushList(String[] registrationID, String content,
			Map extras) throws Exception {
		getPushClient();
		return client.sendPush(PushPayload
				.newBuilder()
				.setPlatform(Platform.all())
				.setAudience(Audience.registrationId(registrationID))
				.setNotification(Notification.alert(content))
				.setMessage(
						Message.newBuilder().setMsgContent(content)
								.addExtras(extras).build()).build());
	}
}
